package com.team.service.generator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Collections;

@Component
public class RedisIdGenerator {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private DefaultRedisScript<String> idGeneratorScript;

    /**
     * 生成唯一ID
     * @return 唯一ID
     */
    public Long generateId() {
        String result = redisTemplate.execute(idGeneratorScript, Collections.emptyList());
        try {
            // 使用BigDecimal处理科学计数法格式的字符串
            BigDecimal bd = new BigDecimal(result);
            return bd.longValue();
        } catch (Exception e) {
            throw new RuntimeException("生成ID失败: " + e.getMessage(), e);
        }
    }
}
